package com.ptt.sqm.ws;

import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.ksoap2.serialization.PropertyInfo;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

/**
 * @author AndroidExample DotNetWebService Class
 * 
 */
@SuppressLint("NewApi")
public class DownloadCall implements IDefaulCall {

	private static DownloadCall singleton;

	public AsyncResponse delegate = null;

	public static DownloadCall getInstance() {
		if (singleton == null) {
			singleton = new DownloadCall();
		}

		return singleton;
	}

	public DownloadCall() {
	}

	public Bitmap execute(String method, PropertyInfo[] params) {
		// initilize the default HTTP client object
		final DefaultHttpClient client = new DefaultHttpClient();

		// forming a HttoGet request
		final HttpGet getRequest = new HttpGet(method);
		try {

			HttpResponse response = client.execute(getRequest);

			// check 200 OK for success
			final int statusCode = response.getStatusLine().getStatusCode();

			if (statusCode != HttpStatus.SC_OK) {
				Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + method);
				return null;

			}

			final HttpEntity entity = response.getEntity();
			final Bitmap bitmap;
			if (entity != null) {
				InputStream inputStream = null;
				try {
					// getting contents from the stream
					inputStream = entity.getContent();
					// decoding stream data back into image Bitmap that
					// android understands
					bitmap = BitmapFactory.decodeStream(inputStream);

				} finally {
					if (inputStream != null) {
						inputStream.close();
					}
					entity.consumeContent();
				}

				return bitmap;
			}
		} catch (Exception e) {
			// You Could provide a more explicit error message for
			// IOException
			getRequest.abort();
			Log.e("DownloadTask", "Something went wrong while" + " retrieving bitmap from " + method + e.toString());
		}

		return null;
	}

}
